#include <pthread.h>
#include <stdio.h>
#include <string.h>

#include "queue.h"
#include "logger.h"

static void *log_main_loop(void *logger) {
	char *mes;
	// TODO(sonya): timouts implementation is temporary(to check for memleaks and some other problems)
	// Logging should stop only with Ctrl+C signal
#if 1
	int time = mget_time(), timeout;
#endif
	while (1) {
		if (!(mes = dequeue(logg.queue))) {
#if 1
			timeout = (mget_time() - time);
			if (timeout > 10)
				return NULL;
#endif
			continue;
		}
		fprintf(logg.file, "%s\n", mes);
#if 1
		time = mget_time();
#endif
	}
	return NULL;
}

void log_init(int log_level, const char *log_file) {
	memset(&logg, 0, sizeof(logg));
	logg.queue = queue_create();
	if ((!log_level) || (log_level > EMERG))
		logg.log_level = WARNING;
	else
		logg.log_level = log_level;

	if (log_file)
		logg.file = fopen(log_file, "w");

	if (!logg.file)
		logg.file = stderr;

	pthread_create(&logg.tid, NULL, &log_main_loop, NULL);
}

void log_deinit(void) {
	queue_destroy(logg.queue);
	fclose(logg.file);
}
